package kwic;

import kwic.architecture.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class KWICGUI extends JFrame {
    private JComboBox<String> methodComboBox;
    private JButton runButton;
    private JButton infoButton;
    private JTextArea outputArea;
    private JTextArea infoArea;
    private JButton inputButton;
    private String inputText = "";

    public KWICGUI() {
        super("KWIC System");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLayout(new BorderLayout());

        // Output area
        outputArea = new JTextArea(10, 40);
        outputArea.setEditable(false);

        // Method selection
        String[] methods = {"Main Program - Subroutine", "Object-Oriented", "Event System", "Pipe-Filter"};
        methodComboBox = new JComboBox<>(methods);
        runButton = new JButton("Run");
        runButton.addActionListener(new RunButtonListener());

        // Info area
        infoButton = new JButton("Show Info");
        infoButton.addActionListener(new InfoButtonListener());
        infoArea = new JTextArea(20, 40);
        infoArea.setEditable(false);

        // Input button
        inputButton = new JButton("Input Text");
        inputButton.addActionListener(new InputButtonListener());

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        topPanel.add(inputButton, BorderLayout.WEST);
        topPanel.add(methodComboBox, BorderLayout.CENTER);
        topPanel.add(runButton, BorderLayout.EAST);

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout());
        centerPanel.add(new JScrollPane(outputArea), BorderLayout.NORTH);
        centerPanel.add(infoButton, BorderLayout.CENTER);
        centerPanel.add(new JScrollPane(infoArea), BorderLayout.SOUTH);

        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
    }

    private class RunButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String method = (String) methodComboBox.getSelectedItem();
            new KWICWorker(method, inputText).execute();
        }
    }

    private class KWICWorker extends SwingWorker<String, Void> {
        private String method;
        private String inputText;

        public KWICWorker(String method, String inputText) {
            this.method = method;
            this.inputText = inputText;
        }

        @Override
        protected String doInBackground() throws Exception {
            String outputFilePath = "";

            // Write input to file
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/input.txt"))) {
                writer.write(inputText);
            }

            // Run selected method
            if (method.equals("Main Program - Subroutine")) {
                MainProgramSubroutine.main(new String[]{});
                outputFilePath = "src/main/resources/output1.txt";
            } else if (method.equals("Object-Oriented")) {
                ObjectOriented.main(new String[]{});
                outputFilePath = "src/main/resources/output2.txt";
            } else if (method.equals("Event System")) {
                EventSystem.main(new String[]{});
                outputFilePath = "src/main/resources/output3.txt"; // 确保EventSystem类输出文件路径正确
            } else if (method.equals("Pipe-Filter")) {
                PipeFilter.main(new String[]{});
                outputFilePath = "src/main/resources/output4.txt"; // 确保PipeFilter类输出文件路径正确
            }

            // Wait for the output file to be created
            File outputFile = new File(outputFilePath);
            int attempts = 0;
            while (!outputFile.exists() && attempts < 10) {
                try {
                    Thread.sleep(500); // 延迟 500 毫秒
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
                attempts++;
            }

            if (!outputFile.exists()) {
                throw new FileNotFoundException("Output file not found: " + outputFilePath);
            }

            // Read output from file
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(outputFile))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }
            return output.toString();
        }

        @Override
        protected void done() {
            try {
                outputArea.setText(get());
            } catch (Exception e) {
                e.printStackTrace();
                outputArea.setText("Error: " + e.getMessage());
            }
        }
    }

    private class InfoButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String method = (String) methodComboBox.getSelectedItem();
            StringBuilder info = new StringBuilder();
            ImageIcon imageIcon = null;

            if (method.equals("Main Program - Subroutine")) {
                info.append("Main Program - Subroutine:\n")
                        .append("This approach uses a single main program that calls several subroutines.\n\n")
                        .append("Source Code Structure:\n")
                        .append("MainProgramSubroutine.java\n\n")
                        .append("Key Functions:\n")
                        .append(readCode("src/main/java/kwic/architecture/MainProgramSubroutine.java"));
                imageIcon = new ImageIcon("src/main/resources/Main.png");
            } else if (method.equals("Object-Oriented")) {
                info.append("Object-Oriented:\n")
                        .append("This approach uses classes and objects to represent different components of the KWIC system.\n\n")
                        .append("Source Code Structure:\n")
                        .append("ObjectOriented.java\n\n")
                        .append("Key Functions:\n")
                        .append(readCode("src/main/java/kwic/architecture/ObjectOriented.java"));
                imageIcon = new ImageIcon("src/main/resources/mianxiangduixiang.png");
            } else if (method.equals("Event System")) {
                info.append("Event System:\n")
                        .append("This approach uses event-driven programming where components communicate through events.\n\n")
                        .append("Source Code Structure:\n")
                        .append("EventSystem.java\n\n")
                        .append("Key Functions:\n")
                        .append(readCode("src/main/java/kwic/architecture/EventSystem.java"));
                imageIcon = new ImageIcon("src/main/resources/shijianSystem.png");
            } else if (method.equals("Pipe-Filter")) {
                info.append("Pipe-Filter:\n")
                        .append("This approach uses a series of filters connected by pipes, where each filter performs a transformation on the data.\n\n")
                        .append("Source Code Structure:\n")
                        .append("PipeFilter.java\n\n")
                        .append("Key Functions:\n")
                        .append(readCode("src/main/java/kwic/architecture/PipeFilter.java"));
                imageIcon = new ImageIcon("src/main/resources/pipe.png");
            }

            infoArea.setText(info.toString());
            if (imageIcon != null) {
                JLabel picLabel = new JLabel(imageIcon);
                JOptionPane.showMessageDialog(null, picLabel, "Example Image", JOptionPane.PLAIN_MESSAGE);
            }
        }
    }

    private class InputButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            inputText = JOptionPane.showInputDialog(null, "Enter text for KWIC:", "Input Text", JOptionPane.PLAIN_MESSAGE);
            if (inputText == null) {
                inputText = ""; // Handle case where user cancels input
            }
        }
    }

    private String readCode(String filePath) {
        StringBuilder code = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                code.append(line).append("\n");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return code.toString();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            KWICGUI gui = new KWICGUI();
            gui.setVisible(true);
        });
    }
}
